package com.utils;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;

import com.alibaba.fastjson.JSONObject;
import com.crmeb.core.exception.CrmebException;
import com.github.qcloudsms.SmsMultiSender;
import com.github.qcloudsms.SmsResultBase;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.httpclient.HTTPException;
import com.zbkj.crmeb.sms.model.CmsMessageConfig;
import com.zbkj.crmeb.sms.request.SendSmsVo;

public class MessageUtils {
    /**
     * 按模板发送短信 支持单发和群发
     * @param isSingle 是否单发 true: 单发，false: 群发
     * @param form 需要发送的短信内容及收信人手机号
     * @param config 短信配置
     */
    public static void sendMessage(Boolean isSingle, SendSmsVo form, CmsMessageConfig config)  {
        validateMessage(form, config);
        String regex = ";";
        String[] params = new String[]{};
        if(StringUtils.isNotBlank(form.getCaptcha())){
            params = new String[]{form.getCaptcha()};
        }
        if(StringUtils.isNotBlank(form.getParam())){
            List<String> list1 = JSONObject.parseArray(form.getParam(), String.class);
            params = list1.toArray(new String[0]);
        }
        String[] phoneNumbers = form.getMobiles().split(regex);
        SmsResultBase result;
        try {
            String nationCode = StringUtils.isNotBlank(form.getNationCode()) ? form.getNationCode() : "86";
            // 是否单发
            if (isSingle) {
                SmsSingleSender ssender = new SmsSingleSender(config.getAppId(), config.getAppKey());
                result = ssender.sendWithParam(nationCode, phoneNumbers[0], config.getTemplateId(), params, config.getSmsSign(), "", "");
            } else {
                SmsMultiSender msender = new SmsMultiSender(config.getAppId(), config.getAppKey());
                result = msender.sendWithParam(nationCode, phoneNumbers, config.getTemplateId(), params, config.getSmsSign(), "", "");
            }
            System.out.println(result);
        } catch (HTTPException e) {
            e.printStackTrace();
            throw new CrmebException("HTTP响应码错误！");
        } catch (JSONException e) {
            e.printStackTrace();
            throw new CrmebException("json解析错误！");

        } catch (IOException e) {
            e.printStackTrace();
            throw new CrmebException("网络IO错误！");
        }
    }
    /**
     * 校验参数
     */
    private static void validateMessage(SendSmsVo messageForm, CmsMessageConfig messageConfig) {
        //ValidatorUtils.validateEntity(messageForm);
        if (null == messageConfig) {
            throw new CrmebException("系统参数异常！");
        }
    }
}
